package com.company.Lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// tryLock
public class LockDemo1 {
    static Lock lock = new ReentrantLock(); // sync关键字

    public static void main(String args[]) throws InterruptedException {
        for (int i = 0; i < 2; i++) {
            Thread th = new Thread(() -> {
                try {
                    System.out.println(Thread.currentThread() + "准备抢锁 ");
                    if (lock.tryLock(2000, TimeUnit.MILLISECONDS)) { // 等待 一定时间
                        System.out.println(Thread.currentThread() + "拿到锁");
                        Thread.sleep(3_000L);  // TODO 拿到锁开始干活，模拟耗时3秒
                        lock.unlock(); // 解锁
                    } else {
                        System.out.println(Thread.currentThread() + "没抢到锁，有人在执行，算了...");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            th.start();
        }

        Thread.sleep(60000L);
    }

}
